
package ift605.jade.part1Example;

import jade.core.Agent;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;


/**
 * This agent is based on the ThanksAgent example, described as below
 * 
 * This agent has the following functionality: 
 * <ul>
 * <li> registers with the DF
 * <li> creates a list of agents
 * <li> each of this new agents registers with the DF
 * <li> the father agent sends a message of greeting to each of them
 * <li> it waits for an answer to the greeting
 * <li> it thanks the agents that have answered 
 * </ul>
 * @author Fabio Bellifemine, TILab
 * @version $Date: 2009-07-01 15:43:58 +0200 (mer, 01 lug 2009) $ $Revision: 6151 $
 **/
public class ThanksAgent extends Agent {

	public final static String GREETINGS = "That was the worst throw ever. Of all time.";
	public final static String THANKS = "Not my fault. A wall got in my way.";

	protected void setup() {
		
		try {
			System.out.println("Creation of :: " + getLocalName());
			//Register the agent to the DIRECTORY FOLDER
			
			DFAgentDescription dfd = new DFAgentDescription();
			dfd.setName(getAID());
			ServiceDescription sd = new ServiceDescription();
			sd.setType(THANKS);
			sd.setName(THANKS);
			
			dfd.addServices(sd);
			DFService.register(this, dfd);
			System.out.println(getLocalName()+" REGISTERED WITH THE DF");
		} catch (FIPAException e) {
			e.printStackTrace();
		}

		addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				
				ACLMessage msg = receive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
				
				if (msg != null) 
				{
					if (GREETINGS.equalsIgnoreCase(msg.getContent())) {

						System.out.println(myAgent.getLocalName()+" received a message from "+msg.getSender().getLocalName() + " : " + msg.getContent());
						ACLMessage reply = msg.createReply();
						reply.setContent(THANKS);
						myAgent.send(reply);
						
						myAgent.doDelete();
					} 
					else {
						System.out.println(myAgent.getLocalName()+" Unexpected message received from "+msg.getSender().getLocalName()); 
					}					
				}
				else {
					block();
				}
			}
		});
	}

	protected void takeDown() {
		// Deregister with the DF
		try {
			DFService.deregister(this);
			System.out.println(getLocalName()+" DEREGISTERED WITH THE DF");
			System.out.println("Death of :: " + getLocalName());
		} catch (FIPAException e) {
			e.printStackTrace();
		}
	}
}
